package com.xxl.job.executor.service;


import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.common.RedisKeyConstant;
import com.xxl.job.executor.model.PowDownCmd;
import com.xxl.job.executor.utils.JSONUtils;
import com.xxl.job.executor.utils.MapUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class PowDownCmdService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PowDownCmdService powDownCmdService;

    /**
     * 按gatherID取控制命令
     * @param garherId
     * @return
     */
    public List<PowDownCmd> getPowDownCmds(String garherId) {
        List<PowDownCmd> powDownCmds = new ArrayList<>();
        BoundHashOperations<String, String, String> valueOperations = redisTemplate.boundHashOps(RedisKeyConstant.KEY_HASH_POW_DOWN_CMD);
        List<String> values = MapUtil.getLikeByMap(valueOperations.entries(),"CMD_"+garherId);
        for(String value:values){
            if(StringUtils.isNotBlank(value)){
                try {
                    PowDownCmd powDownCmd = JSONUtils.json2pojo(value, PowDownCmd.class);
                    powDownCmds.add(powDownCmd);
                    powDownCmdService.delte(powDownCmd);
                } catch (IOException e) {
                    XxlJobLogger.log("根据garherId取控制命令转换出错");
                }
            }
        }

        return powDownCmds;
    }

    /**
     * 取所有控制命令
     * @return
     */
    public List<PowDownCmd> getPowDownCmds() {
        List<PowDownCmd> powDownCmds = new ArrayList<>();
        BoundHashOperations<String, String, String> valueOperations = redisTemplate.boundHashOps(RedisKeyConstant.KEY_HASH_POW_DOWN_CMD);
        for(String value:valueOperations.entries().values()){
            if(StringUtils.isNotBlank(value)){
                try {
                    PowDownCmd powDownCmd = JSONUtils.json2pojo(value, PowDownCmd.class);
                    if("HK".equals(powDownCmd.getSystemCode())){
                        powDownCmds.add(powDownCmd);
                        powDownCmdService.delte(powDownCmd);
                    }
                } catch (IOException e) {
                    XxlJobLogger.log("取所有控制命令转换出错");
                }
            }
        }

        return powDownCmds;
    }

    public void delte(PowDownCmd powDownCmd) {
        BoundHashOperations<String, String, String> valueOperations = redisTemplate.boundHashOps(RedisKeyConstant.KEY_HASH_POW_DOWN_CMD);
        valueOperations.delete("CMD_"+powDownCmd.getGatherId()+"_"+powDownCmd.getGatherResId()+"_"+powDownCmd.getSignalCode()+"_"+powDownCmd.getCmdStr());
    }
}
